/**
 * author: abid.hussain
 */
exports.GADazzleHandler = Core.Class.singleton({
	classname : 'GADazzleHandler',
	initialize : function (){
		this._loggingCount = 0;
		this._countThreshHold = 0;
		this._timeThreshHold = 0;
		this._logOffers = false;
		this._logTransaction = false;
		this._logEvent = false;
		this._loggingType = null;
		this._storage = null;
		this._prevTime = 0;
		this._transMap =  [];
		this._eventsMap = [];
		this._offersMap = [];
		this._getDazzleInfo();
	},
	
	performInitialization: function(){
		/* Dummy method to call the default init */
	},
	
	_getDazzleInfo : function ()
	{
		try
		{
			var responseObject = GAGameLoader.getResponseObject();
			this._url = responseObject.getDazzleServer();
//			console.log('WARNING !!!!! : Dazzle URL is hardcoded....!!!!!');
//			this._url='http://vmart.gamevstudios.com/addTransactions/';
			this._url = encodeURI(this._url);
			this._countThreshHold = responseObject.getCountThreshold();
			this._timeThreshHold = responseObject.getTimeThreshold();
			this._logOffers = responseObject.getLogOffer();
			this._logTransaction = responseObject.getLogTransaction();
			this._logEvent = responseObject.getLogEvent();
			this._loggingType = parseInt(responseObject.getLoggingType());
			this._storage = new Storage.KeyValue();
			this._storage.getItem(kGADazzle.kGALoggingCount, this.readCountCb.bind(this));
			if(this._loggingCount == 0)
			{
				var date = new Date();
				this._prevTime = date.getTime();
			}
			this._readTransactions();
			this._readEvents();
			this._readOffers();
		}
		catch(exception)
		{
			console.log('Dazzle:: _getDazzleInfo ->'+exception);
		}
	},
	readCountCb: function(error,countValue){
		if(!error){
			this._loggingCount = countValue;
			console.log('Dazzle:: Saved LoggingCount = '+this._loggingCount);
		}else{
			console.log('Dazzle:: READING ERROR = '+error);
		}
	},
	logTransaction: function (transModelObject){
		if (this._logTransaction && this._loggingType != parseInt(GADazzleLoggingType.NoLogging) && transModelObject!= null){	
			this._validateOptionalField(transModelObject, 'user_id', '');
			this.validateField(transModelObject, 'user_level','-1');
			this.validateField(transModelObject, 'item_id','-1');
			this.validateField(transModelObject, 'item_name','');
			this.validateField(transModelObject, 'category_id','-1');
			this.validateField(transModelObject, 'category_name','');
			this.validateField(transModelObject, 'store_id','-1');
			this.validateField(transModelObject, 'store_name','');
			this.validateField(transModelObject, 'currency','-1');
			this.validateField(transModelObject, 'price','-1');
			this._validateOptionalField(transModelObject, 'price_bucket', '');
			this.validateField(transModelObject, 'ts','-1');
			this.validateField(transModelObject, 'quantity','-1');
			transModelObject.state =kGADazzle.kGAPendingLog;
			this._transMap.push(transModelObject);
			var json = JSON.stringify(this._transMap);
			this._loggingCount++;
			this._storage.setItem(kGADazzle.kGALoggingCount,this._loggingCount);
			if(this._loggingCount <= kGADazzle.kGALoggingThreshold){
				this._serializeInfo('transaction', json);	
			}
			if( this._isCountOrCommonMode() ){
				this._processBatch();
			}
			else if( this._isTimeOrCommonMode()){
				this._processBatch();
			}
			else if ( this._isImmediateMode()){
				this._processBatch();
			}
		}
	},
	
	logEvent : function (eventsModelObj){
		if(this._logEvent && this._loggingType != parseInt(GADazzleLoggingType.NoLogging) && eventsModelObj != null)
		{
			this.validateField(eventsModelObj, 'event_type', '-1');
			this._validateOptionalField(eventsModelObj, 'user_id', '-1');
			this.validateField(eventsModelObj, 'user_level', '-1');
			this._validateOptionalField(eventsModelObj, 'p_curr_bal', '-1');
			this._validateOptionalField(eventsModelObj, 's_curr_bal', '-1');
			this.validateField(eventsModelObj, 'ts', '-1');
			this._validateOptionalField(eventsModelObj, 'p_1', '');
			this._validateOptionalField(eventsModelObj, 'p_2', '');
			this._validateOptionalField(eventsModelObj, 'p_3', '');
			eventsModelObj.state = kGADazzle.kGAPendingLog;
			this._eventsMap.push(eventsModelObj);
			var json = JSON.stringify(this._eventsMap);
			this._loggingCount ++;
			this._storage.setItem(kGADazzle.kGALoggingCount,this._loggingCount);
			if(this._loggingCount <= kGADazzle.kGALoggingThreshold){
				this._serializeInfo('event', json);
			}
			if( this._isCountOrCommonMode() ){
				this._processBatch();
			}
			else if(this._isTimeOrCommonMode()){
				this._processBatch();
			}
			else if (this._isImmediateMode()){
				this._processBatch();
			}
		}
	},
	
	logOffer : function (offerObj)
	{
		if(this._logOffers && this._loggingType != parseInt(GADazzleLoggingType.NoLogging) && offerObj != null)
		{	
			var value = "";
			this.validateField(offerObj, 'fire_type', '-1');
			this._validateOptionalField(offerObj, 'user_id', '');
			this.validateField(offerObj, 'user_level', '-1');
			this.validateField(offerObj, 'currency', '-1');
			this._validateOptionalField(offerObj, 'offer_id', '');
			this._validateOptionalField(offerObj, 'i_tx_id', '');
			this._validateOptionalField(offerObj, 'i_price_tier', '');
			this.validateField(offerObj, 'ts', '-1');
			this.validateField(offerObj, 'currency_name', '');
			offerObj.state = kGADazzle.kGAPendingLog;
			this._offersMap.push(offerObj);
			var json = JSON.stringify(this._offersMap);
			this._loggingCount ++;
			this._storage.setItem(kGADazzle.kGALoggingCount,this._loggingCount);
			if(this._loggingCount <= kGADazzle.kGALoggingThreshold){
				this._serializeInfo('offer', json);
			}
			if( this._isCountOrCommonMode() ){		
				this._processBatch();
			}
			else if( this._isTimeOrCommonMode() ){
				this._processBatch();
			}
			else if ( this._isImmediateMode() ){
				this._processBatch();
			}
		}
	},
	validateField: function(thisp, fieldName, value) {
		var data = thisp[fieldName];
		if (data == null || data=="" ) {
			thisp[fieldName] = value;
			thisp["isError"] = "1";
		}
	},
	_validateOptionalField: function(thisp, fieldName, value){
		var data = thisp[fieldName];
		if (data == null || data=="" ) {
			thisp[fieldName] = value;
		}
	},
	_processBatch : function (){
		var transArray =[];
		var eventsArray =[];
		var offersArray = [];
		var length = "";
		try{
			length = this._transMap.length;
			for(var i=0; i<length; i++){
				var obj = this._transMap[i];
				if(obj!= undefined && obj.state != kGADazzle.kGAInProgressLog){
					transArray.push(obj);
					obj.state=kGADazzle.kGAInProgressLog;
				}
			}
			length = this._eventsMap.length;
			for(var i=0; i<length; i++){
				var obj = this._eventsMap[i];
				if(obj!= undefined && obj.state != kGADazzle.kGAInProgressLog){
					eventsArray.push(obj);
					obj.state=kGADazzle.kGAInProgressLog;
				}
			}
			length= this._offersMap.length;
			for(var i=0; i<length; i++){
				var obj = this._offersMap[i];
				if(obj!= undefined && obj.state != kGADazzle.kGAInProgressLog){
					offersArray.push(obj);
					obj.state=kGADazzle.kGAInProgressLog;
				}
			}
			var commonModelObj = new GACommonModel();
			commonModelObj.setCommonParams();
			commonModelObj.setTransactions(transArray);
			commonModelObj.setEvents(eventsArray);
			commonModelObj.setOffers(offersArray);
			var jsonData = JSON.stringify(commonModelObj);
			var encodedData = encodeURIComponent(jsonData);
			var params = "json="+ encodedData;
			var webFetcher = new GAWebFetcher(this, 15, 0);
			webFetcher.invokePostRequest(this._url,params,true);
		}catch(exception){
			console.log('GALOGGER:: _processBatch ->'+exception);
		}
	},
	_isCountOrCommonMode : function (){
		var mode = false;
		if(this._loggingCount == this._countThreshHold && ( (this._loggingType == parseInt(GADazzleLoggingType.CountThreshold)) || (this._loggingType == parseInt(GADazzleLoggingType.BothCountAndTimeThreshold)) ))
		{
			mode = true;
		}
		return mode;
	},
	_isTimeOrCommonMode : function (){
		var mode = false;
		var date = new Date();
		var timeCount = (date.getTime() - this._prevTime)/1000;
		if( timeCount >= this._timeThreshHold && ( (this._loggingType == parseInt(GADazzleLoggingType.TimeThreshold)) || (this._loggingType == parseInt(GADazzleLoggingType.BothCountAndTimeThreshold)) ))
		{
			mode = true;
		}
		return mode;
	},
	_isImmediateMode : function (){
		var mode = false;
		if( this._loggingType == parseInt(GADazzleLoggingType.Immediate) )
		{
			mode = true;
		}
		return mode;
	},
	_onApplicationTerminate : function ()
	{
		if( this._loggingType == parseInt(GADazzleLoggingType.OnApplicationTermination) )
		{
			ProcessBatch();
		}
	},
	_serializeInfo : function (name,info){
		Storage.FileSystem.writeFile('./Content/Dazzle/'+name+'.json', info);
	},
	_readTransactions : function (){
		Storage.FileSystem.readFile('./Content/Dazzle/transaction.json', false, this.readTransComplete.bind(this));
	},
	_readOffers : function (){
		Storage.FileSystem.readFile('./Content/Dazzle/offer.json', false, this.readOffersComplete.bind(this));
	},
	_readEvents : function (){
		Storage.FileSystem.readFile('./Content/Dazzle/event.json', false, this.readEventsComplete.bind(this));
	},
	
	readTransComplete : function (error,contents)
	{
		if(!error)
		{
			if (contents.length > 0)
			{
				var transArray = eval("(" + contents + ")");
				var length = transArray.length;
				for(var i=0; i<length; i++)
				{
					var obj = transArray[i];
					if(obj != undefined)
					{
						obj.state =kGADazzle.kGAPendingLog;
						this._transMap.push(obj);
					}
				}
			}
		}
	},
	
	
	readEventsComplete: function (error,contents)
	{
		if(!error)
		{
			if (contents.length > 0)
			{
				var eventsArray = eval("(" + contents + ")");
				var length = eventsArray.length;
				for(var i=0; i<length; i++)
				{
					var obj = eventsArray[i];
					if(obj != undefined)
					{
						obj.state =kGADazzle.kGAPendingLog;
						this._eventsMap.push(obj);
					}
				}
			}
		}
	},
	
	readOffersComplete: function (error,contents)
	{
		if(!error)
		{
			if (contents.length > 0)
			{
				var offersArray = eval("(" + contents + ")");
				var length = offersArray.length;
				for(var i=0; i<length; i++)
				{
					var obj = offersArray[i];
					if(obj != undefined)
					{
						obj.state =kGADazzle.kGAPendingLog;
						this._offersMap.push(obj);
					}
				}
			}
		}
	},
	
	_revertBatch: function(){
		var length = this._transMap.length;
		for(var i=0; i<length; i++){
			var obj = this._transMap[i];
			if(obj != undefined && obj.state == kGADazzle.kGAInProgressLog){
				obj.state = kGADazzle.kGAPendingLog;
			}
		}
		length = this._eventsMap.length;
		for(var i=0; i<length; i++){
			var obj = this._eventsMap[i];
			if(obj != undefined && obj.state == kGADazzle.kGAInProgressLog){
				obj.state = kGADazzle.kGAPendingLog;
			}
		}
		length = this._offersMap.length;
		for(var i=0; i<length; i++){
			var obj = this._offersMap[i];
			if(obj != undefined && obj.state == kGADazzle.kGAInProgressLog){
				obj.state = kGADazzle.kGAPendingLog;
			}
		}
	},
	
	webFetchSuccess: function (webFetcher, response){
		console.log('Dazzle: webFetchSuccess AND response - > '+response);
		var transArray=[];
		var eventsArray=[];
		var offersArray=[];
		var respStatus = "";
		try{
			respStatus = response.match("status=\"SUCCESS\"");
			if(respStatus != -1){
				this._loggingCount = 0;
				this._storage.setItem(kGADazzle.kGALoggingCount,this._loggingCount);
				var date = new Date();
				this._prevTime = date.getTime();
				var length = this._transMap.length;
				for(var i=0; i<length; i++){
					var obj= this._transMap[i];
					if(obj!=undefined && obj!=null){
						if(obj.state == kGADazzle.kGAInProgressLog){
							this._transMap.splice(i, 1);
						}else if(obj.state != undefined){
							transArray.push(obj);
						}
					}
				}
				length = this._eventsMap.length;
				for(var i=0; i<length; i++){
					var obj = this._eventsMap[i];
					if(obj!=undefined && obj!=null){
						if(obj.state == kGADazzle.kGAInProgressLog){
							this._eventsMap.splice(i, 1);
						}else if(obj.state != undefined){
							eventsArray.push(obj);
						}
					}
				}
				length = this._offersMap.length;
				for(var i=0; i<length; i++){
					var obj = this._offersMap[i];
					if(obj!=undefined&&obj!=null){
						if(obj.state == kGADazzle.kGAInProgressLog){
							this._offersMap.splice(i, 1);
						}else if(obj.state != undefined){
							offersArray.push(obj);
						}
					}
				}
				this._serializeInfo('transaction', transArray);
				this._serializeInfo('event', eventsArray);
				this._serializeInfo('offer', offersArray);
			}else{
				console.log("Dazzle: Server Response is Error");
				this._revertBatch();
			}
		}catch(exception){
			console.log('Dazzle: webFetchSuccess ->'+exception);
		}
	},

	webFetchFailure: function (webFetcher, error){
		console.log('GALOGGER: webFetchFailure AND response - > '+ error);
		this._revertBatch();
	},
	
	destroy: function(){
		var length = this._transMap.length;
		for(var i=0; i<length; i++){
			this._transMap[i].destroy();
			delete this._transMap[i];
		}
		delete this._transMap;
		length = this._eventsMap.length;
		for(var i=0; i<length; i++){
			this._eventsMap[i].destroy();
			delete this._eventsMap[i];
		}
		delete this._eventsMap;
		length = this._offersMap.length;
		for(var i=0; i<length; i++){
			this._offersMap[i].destroy();
			delete this._offersMap[i];
		}
		delete this._offersMap;
		this._loggingCount = null;
		this._storage = null;
		this._countThreshHold = null;
		this._timeThreshHold = null;
		this._logOffers = null;
		this._logTransaction = null;
		this._logEvent = null;
		this._loggingType = null;
		this._prevTime = null;
	}
});